package gitee.derumin.railway_accelerator.mixin;

import net.minecraft.entity.EntityType;
import net.minecraft.entity.vehicle.AbstractMinecartEntity;
import net.minecraft.entity.vehicle.HopperMinecartEntity;
import net.minecraft.entity.vehicle.StorageMinecartEntity;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

@Mixin(HopperMinecartEntity.class)
public abstract class HopperMinecartEntityMixin extends StorageMinecartEntity {
    @Shadow public abstract boolean isEnabled();

    @Shadow public abstract boolean canOperate();

    protected HopperMinecartEntityMixin(EntityType<?> entityType, World world) {
        super(entityType, world);
    }

    @Inject(method = "tick", at = @At("HEAD"), cancellable = true)
    private void st(CallbackInfo ci){
        if (this.railway_accelerator$getTrain() != null){
            super.tick();
            ci.cancel();
        }
    }

    @Override
    public ConnectionStatus railway_accelerator$follow(AbstractMinecartEntity goal, double delta, boolean firstMove){
        ConnectionStatus status = super.railway_accelerator$follow(goal, delta, firstMove);
        if (!this.getWorld().isClient && this.isAlive() && this.isEnabled() && this.canOperate()) {
            this.markDirty();
        }
        return status;
    }

    @Override
    public double railway_accelerator$moveOneStep(double tickRemains, boolean firstMove){
        double deltaCost = super.railway_accelerator$moveOneStep(tickRemains, firstMove);
        if (!this.getWorld().isClient && this.isAlive() && this.isEnabled() && this.canOperate()) {
            this.markDirty();
        }
        return deltaCost;
    }
}
